<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <el-page-header
          :content="this.$route.query.id ? '编辑企业' : '增加企业'"
          @back="$router.back()"
        />

      </div>

      <div class="right">
        黑马程序员
      </div>

    </header>

    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>

        <div class="form">
          <el-form ref="ruleForm" label-width="100px" :model="addForm" :rules="addRules">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>

            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>

            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>

            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :value="item.industryCode"
                  :label="item.industryName"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>

            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>

            <el-form-item label="营业执照" prop="businessLicenseId">
              <!-- :before-upload="beforeUpload"上传前校验文件 -->
              <el-upload
                action="#"
                :file-list="fileList"
                :http-request="uploadRequest"
                :before-upload="beforeUpload"
                list-type="picture-card"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button>重置</el-button>
        <el-button type="primary" @click="addOK">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { getIndustryListAPI,
  uploadAPI,
  createExterpriseAPI,
  getEnterpriseDetailAPI,
  editExterpriseAPI } from '@/api/enterprise'
export default {
  data() {
    return {
      addForm: {
        name: '', // 企业名称
        legalPerson: '', // 法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 所在行业
        contact: '', // 企业联系人
        contactNumber: '', // 联系人电话
        businessLicenseUrl: '', // 营业执照url
        businessLicenseId: '' // 营业执照id
      },
      industryList: [], // 可选行业列表
      fileList: [], // 营业执照列表
      addRules: {
        name: [
          { required: true, message: '企业名称为必填', trigger: 'blur' }
        ],
        legalPerson: [
          { required: true, message: '法人为必填', trigger: 'blur' }
        ],
        registeredAddress: [
          { required: true, message: '注册地址为必填', trigger: 'blur' }
        ],
        industryCode: [
          { required: true, message: '所在行业为必填', trigger: 'change' }
        ],
        contact: [
          { required: true, message: '企业联系人为必填', trigger: 'blur' }
        ],
        contactNumber: [
          { required: true, message: '企业联系人电话为必填', trigger: 'blur' },
          { pattern: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
            message: '请输入正确的手机号', trigger: 'blur'
          }
        ],
        businessLicenseId: [
          { required: true, message: '请上传营业执照', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getIndustryList()
    if (this.$route.query.id) {
      this.confirm()
    }
  },
  methods: {
    // 行业列表
    async getIndustryList() {
      const res = await getIndustryListAPI()
      this.industryList = res.data
    },
    // 上传前校验
    beforeUpload(file) {
      console.log(file)
      const fileType = ['image/jpeg', 'image/png', 'image/jpg']
      const max = 5 * 1024 * 1024
      const A = fileType.includes(file.type)
      const B = file.size <= max
      if (!A) {
        this.$message.error('上传合同图片只能是 PNG/JPG/JPEG 格式!')
      }
      if (!B) {
        this.$message.error('上传合同图片大小不能超过 5MB!')
      }
      return A && B
    },
    // 上传文件
    async uploadRequest(data) {
      // console.log(data.file)
      const formData = new FormData()
      formData.append('file', data.file)
      formData.append('type', 'businessLicense')
      // 调接口 formData是要传的数据
      const res = await uploadAPI(formData)
      // console.log(res)
      this.addForm.businessLicenseUrl = res.data.url
      this.addForm.businessLicenseId = res.data.id
      this.$refs.ruleForm.validate(isOK => {
        console.log(isOK)
      })
    },
    // 新增企业
    addOK() {
      this.$refs.ruleForm.validate(async isOK => {
        if (isOK) {
          if (!this.$route.query.id) {
            const res = await createExterpriseAPI(this.addForm)
            // console.log(res)
            if (res.code === 10000) {
              this.$message.success('新增成功')
              this.$router.back()
            } else {
              this.$message.error('新增失败，' + res.msg)
            }
          } else {
            await editExterpriseAPI({
              ...this.addForm,
              id: this.$route.query.id
            })
            this.$message.success('编辑成功')
            this.$router.back()
          }
        }
      })
    },
    // 回填数据
    async confirm() {
      if (this.$route.query.id) {
        const res = await getEnterpriseDetailAPI(this.$route.query.id)
        console.log(res)
        this.addForm.name = res.data.name
        this.addForm.legalPerson = res.data.legalPerson
        this.addForm.registeredAddress = res.data.registeredAddress
        this.addForm.industryCode = res.data.industryCode
        this.addForm.contact = res.data.contact
        this.addForm.contactNumber = res.data.contactNumber
        this.addForm.businessLicenseUrl = res.data.businessLicenseUrl
        this.addForm.businessLicenseId = res.data.businessLicenseId
        this.fileList = [{
          name: res.data.businessLicenseName,
          url: res.data.businessLicenseUrl
        }]
      }
    }
  }
}
</script>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    align-items: center;
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }
      .arrow{
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left:20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form{
          display: flex;
          flex-wrap: wrap;
          .el-form-item{
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
